package com.zjf.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException;
import com.zjf.dao.CookieDao;
import com.zjf.db.DBManager;

public class CookieDaoImpl implements CookieDao {
	private Connection conn;

	public boolean add(String username, String id) throws Exception {
		PreparedStatement stmt = null;
		try {
			conn = DBManager.getConnection();
			stmt = conn.prepareStatement("insert into b_cookie values(null,?,?) ");
			stmt.setString(1, username);
			stmt.setString(2, id);
			stmt.executeUpdate();
			return true;
		} finally {
			DBManager.close(conn, stmt);
		}

	}

	public String get(String username) throws Exception {
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			conn = DBManager.getConnection();
			stmt = conn.prepareStatement("select * from b_cookie where c_username = ? order by id desc");
			stmt.setString(1, username);
			rs = stmt.executeQuery();
			if (rs.next()) {
				String id = rs.getString(3);

				return id;
			}
			return null;
		} finally {
			DBManager.close(conn, stmt, rs);
		}
	}

	public boolean clear(String username) throws Exception {
		PreparedStatement stmt = null;
		try {
			conn = DBManager.getConnection();
			stmt = conn.prepareStatement("delete from b_cookie where c_username = ? ");
			stmt.setString(1, username);
			stmt.executeUpdate();

			return true;
		} catch (MySQLSyntaxErrorException e) {
			System.out.println(e.getMessage());
			return false;

		} finally {
			DBManager.close(conn, stmt);
		}

	}

}
